import { defineStore } from 'pinia'
import axios from 'axios'

export const useMovieStore = defineStore('movie', {
  state: () => ({
    trendingMovies: [],
    currentMovie: null,
    recommendations: [],
    loading: false,
    error: null,
    currentPage: 1,
    hasMore: true,
    pageSize: 12
  }),

  actions: {
    async fetchTrendingMovies(isLoadMore = false) {
      if (!isLoadMore) {
        this.currentPage = 1
        this.hasMore = true
        this.trendingMovies = []
      }
      
      if (!this.hasMore || this.loading) return

      this.loading = true
      this.error = null
      try {
        const response = await axios.get(`http://localhost:8000/api/movies/trending`, {
          params: {
            page: this.currentPage,
            page_size: this.pageSize
          }
        })
        
        if (isLoadMore) {
          this.trendingMovies = [...this.trendingMovies, ...response.data.movies]
        } else {
          this.trendingMovies = response.data.movies
        }
        
        this.hasMore = response.data.has_more
        if (this.hasMore) {
          this.currentPage++
        }
      } catch (error) {
        this.error = '获取热门电影失败'
        console.error('Failed to fetch trending movies:', error)
      } finally {
        this.loading = false
      }
    },

    async fetchMovieDetails(movieId) {
      this.loading = true
      this.error = null
      try {
        const response = await axios.get(`http://localhost:8000/api/movies/${movieId}`)
        this.currentMovie = response.data
      } catch (error) {
        this.error = '获取电影详情失败'
        console.error('Failed to fetch movie details:', error)
      } finally {
        this.loading = false
      }
    },

    async fetchRecommendations(movieId) {
      this.loading = true
      this.error = null
      try {
        const response = await axios.get(`http://localhost:8000/api/movies/${movieId}/recommendations`)
        this.recommendations = response.data
      } catch (error) {
        this.error = '获取电影推荐失败'
        console.error('Failed to fetch recommendations:', error)
      } finally {
        this.loading = false
      }
    }
  }
}) 